<template>
  <div class="layout-pool">
    <div
      class="content"
      v-for="list in systemKeyForElementList"
      :key="list.title"
    >
      <h4>
        {{ list.title }}
      </h4>

      <div :class="list.type === 'full' ? 'full-layout' : 'default-layout'">
        <div
          class="flex-container"
          v-for="(item, index) in list.keyForList"
          :key="index"
          @mousedown="handleMoveDownElement(item, $event)"
          style="cursor: all-scroll"
        >
          <div class="left-element" v-if="item.image">
            <img :src="item.image" alt="" />
          </div>
          <div class="right-container">
            <div class="right-top-element">
              <img
                :src="BiArrowsMove"
                alt=""
                style="width: 12px; height: 12px"
                ref="moveElement"
              />
            </div>
            <div class="right-bottom-element">
              <p>{{ item.name }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FlatColorIconsEditImage from '@/assets/image/FlatColorIconsEditImage.png'
import FlatColorIconsList from '@/assets/image/FlatColorIconsList.png'
import BiArrowsMove from '@/assets/image/BiArrowsMove.png'
import useInsertFromCreateSelection from '@/views/Editor/Canvas/hooks/useInsertFromCreateSelection'
import {
  scoreTotalElement,
  scoreSubCountElement,
  scoreDescriptionElement,
  getScoreFixedKey,
  SCORE_FIXED_KEY,
} from '@/mocks/customElement/score'
import {
  SYSTEM_FIXED_KEY,
  logoElement,
  getSystemFixedKey,
  systemDescElement,
  systemTitleElement,
  systemImageElement,
} from '@/mocks/customElement/system'
import { getEquipFixedKey, equipDescElement } from '@/mocks/customElement/equip'
import {
  tableElementWithAll,
  tableElementWithSoftEquip,
  tableElementWithEquipHardTravel,
} from '@/mocks/customElement/quote'

import { useSlidesStore, useProposalStore } from '@/store'
import { computed, ref } from 'vue'
import type { PPTElement } from '@/types/slides'
import message from '@/utils/message'
const slidesStore = useSlidesStore()
const { layoutType } = useProposalStore()

const viewportRef = ref<HTMLElement>()
viewportRef.value =
  (document.querySelector('.viewport') as HTMLElement) || undefined
const { formatCreateSelection } = useInsertFromCreateSelection(viewportRef)

interface IKeyForElement {
  type?: 'full' | 'default'
  title: string
  keyForList: Array<{
    name: string
    image?: string
    add?: (left: number, top: number) => void
  }>
}

interface IData {
  [key: string]: IKeyForElement
}

const DataOfType: IData = {
  system1: {
    title: '子系统布局',
    keyForList: [
      {
        image: FlatColorIconsEditImage,
        name: 'logo',
        add: (left: number, top: number) =>
          slidesStore.addElement(logoElement({ left, top })),
      },
      {
        image: FlatColorIconsList,
        name: '系统名称',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemTitleElement(getSystemFixedKey('系统名称'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsEditImage,
        name: '系统图片',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemImageElement(getSystemFixedKey('系统图片'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '系统功能介绍',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemDescElement(getSystemFixedKey('系统功能介绍'), { left, top }),
          ),
      },
    ],
  },
  system2: {
    title: '子系统功能布局',
    keyForList: [
      {
        image: FlatColorIconsEditImage,
        name: '功能图片',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'image') return false
              return item.replaceSrc?.includes(SYSTEM_FIXED_KEY['功能图片'])
            },
          )
          const index = currentSlideElement?.length || 0
          return slidesStore.addElement(
            systemImageElement(getSystemFixedKey('功能图片', index), {
              left,
              top,
              width: 90,
              height: 90,
            }),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '功能名称',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content?.includes(SYSTEM_FIXED_KEY['功能名称'])
            },
          )
          const index = currentSlideElement?.length || 0
          return slidesStore.addElement(
            systemTitleElement(getSystemFixedKey('功能名称', index), {
              left,
              top,
            }),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '功能介绍',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content?.includes(SYSTEM_FIXED_KEY['功能描述'])
            },
          )
          const index = currentSlideElement?.length || 0
          return slidesStore.addElement(
            systemDescElement(getSystemFixedKey('功能描述', index), {
              left,
              top,
            }),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '功能单价',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content?.includes(SYSTEM_FIXED_KEY['功能单价'])
            },
          )
          const index = currentSlideElement?.length || 0
          return slidesStore.addElement(
            systemDescElement(getSystemFixedKey('功能单价', index), {
              left,
              top,
            }),
          )
        },
      },
    ],
  },
  system3: {
    title: 'AI接口返回数据布局',
    keyForList: [
      {
        image: FlatColorIconsList,
        name: '过渡句',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemDescElement(getSystemFixedKey('过渡句'), { left, top }),
          ),
      },
    ],
  },
  system4: {
    title: '评分内容提案信息布局',
    keyForList: [
      {
        image: FlatColorIconsList,
        name: '系统描述',
        add: (left: number, top: number) => {
          slidesStore.addElement(
            scoreDescriptionElement(getSystemFixedKey('系统描述'), {
              left,
              top,
            }),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '系统价值',
        add: (left: number, top: number) => {
          slidesStore.addElement(
            scoreDescriptionElement(getSystemFixedKey('系统价值'), {
              left,
              top,
            }),
          )
        },
      },
    ],
  },
  equipment: {
    title: '设备布局',
    keyForList: [
      {
        image: FlatColorIconsEditImage,
        name: 'logo',
        add: (left: number, top: number) =>
          slidesStore.addElement(logoElement({ left, top })),
      },
      {
        image: FlatColorIconsList,
        name: '设备名称',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemTitleElement(getEquipFixedKey('设备名称'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsEditImage,
        name: '设备图片',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            systemImageElement(getEquipFixedKey('设备图片'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '设备介绍',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('设备介绍'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '设备品牌',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('设备品牌'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '设备编码',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('设备编码'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '设备型号',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('设备型号'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '性能参数',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('性能参数'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '设备单价',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('设备单价'), { left, top }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '库存数量',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            equipDescElement(getEquipFixedKey('库存数量'), { left, top }),
          ),
      },
    ],
  },
  score1: {
    title: '总分页布局',
    keyForList: [
      {
        image: FlatColorIconsList,
        name: '总得分',
        add: (left: number, top: number) =>
          slidesStore.addElement(scoreTotalElement({ left, top })),
      },
      {
        image: FlatColorIconsList,
        name: '总得分分析',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            scoreDescriptionElement(getScoreFixedKey('总得分分析'), {
              left,
              top,
            }),
          ),
      },
      {
        image: FlatColorIconsList,
        name: '要素得分',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content.includes(SCORE_FIXED_KEY['要素名称'])
            },
          )
          const index = currentSlideElement?.length || 0
          slidesStore.addElement(
            scoreSubCountElement(
              getScoreFixedKey('要素名称', index),
              getScoreFixedKey('要素得分', index),
              {
                left,
                top,
              },
            ),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '要素得分分析',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content.includes(SCORE_FIXED_KEY['要素得分分析'])
            },
          )
          const index = currentSlideElement?.length || 0
          slidesStore.addElement(
            scoreDescriptionElement(getScoreFixedKey('要素得分分析', index), {
              left,
              top,
            }),
          )
        },
      },
    ],
  },
  score2: {
    title: '要素页布局',
    keyForList: [
      {
        image: FlatColorIconsList,
        name: '要素得分',
        add: (left: number, top: number) => {
          slidesStore.addElement(
            scoreSubCountElement(
              getScoreFixedKey('要素名称'),
              getScoreFixedKey('要素得分'),
              {
                left,
                top,
              },
            ),
          )
        },
      },
      {
        image: FlatColorIconsList,
        name: '痛点描述',
        add: (left: number, top: number) => {
          slidesStore.addElement(
            scoreDescriptionElement(getScoreFixedKey('痛点描述'), {
              left,
              top,
            }),
          )
        },
      },
      // {
      //   image: FlatColorIconsList,
      //   name: '要素得分分析',
      //   add: (left: number, top: number) => {
      //     const currentSlideElement = slidesStore.currentSlide.elements.filter(
      //       (item: PPTElement) => {
      //         if (item.type !== 'text') return false
      //         return item.content.includes(SCORE_FIXED_KEY['要素得分分析'])
      //       },
      //     )
      //     const index = currentSlideElement?.length || 0
      //     slidesStore.addElement(
      //       scoreDescriptionElement(getScoreFixedKey('要素得分分析', index), {
      //         left,
      //         top,
      //       }),
      //     )
      //   },
      // },
      {
        image: FlatColorIconsList,
        name: '指标得分',
        add: (left: number, top: number) => {
          const currentSlideElement = slidesStore.currentSlide.elements.filter(
            (item: PPTElement) => {
              if (item.type !== 'text') return false
              return item.content.includes(SCORE_FIXED_KEY['指标名称'])
            },
          )
          const index = currentSlideElement?.length || 0
          slidesStore.addElement(
            scoreSubCountElement(
              getScoreFixedKey('指标名称', index),
              getScoreFixedKey('指标得分', index),
              {
                left,
                top,
              },
            ),
          )
        },
      },
      // {
      //   image: FlatColorIconsList,
      //   name: '指标得分分析',
      //   add: (left: number, top: number) => {
      //     slidesStore.addElement(
      //       scoreDescriptionElement(getScoreFixedKey('指标得分分析'), {
      //         left,
      //         top,
      //       }),
      //     )
      //   },
      // },
    ],
  },

  quote: {
    title: '报价单类型',
    type: 'full',
    keyForList: [
      {
        name: '软件+硬件+施工',
        add: (left: number, top: number) =>
          slidesStore.addElement(tableElementWithAll({ left, top })),
      },
      {
        name: '软件+硬件',
        add: (left: number, top: number) =>
          slidesStore.addElement(tableElementWithSoftEquip({ left, top })),
      },
      {
        name: '硬件+施工',
        add: (left: number, top: number) =>
          slidesStore.addElement(
            tableElementWithEquipHardTravel({ left, top }),
          ),
      },
    ],
  },
}

const systemKeyForElementList = computed(() => {
  if (!layoutType) return []
  switch (layoutType) {
    case 1:
      return [DataOfType.system1, DataOfType.system2, DataOfType.system3, DataOfType.system4]
    case 2:
      return [DataOfType.equipment]
    case 3:
      return [DataOfType.score1, DataOfType.score2]
    case 4:
      return [DataOfType.system1, DataOfType.system2, DataOfType.energy]
    case 5:
      return [DataOfType.quote]
    default:
      return []
  }
})

const handleMoveDownElement = (
  item: IKeyForElement['keyForList'][number],
  event: { preventDefault: () => void; pageX: any; pageY: any },
) => {
  event.preventDefault()
  if (!item.add) return message.error('该元素目前无法添加，请联系管理员')

  const startPageX = event.pageX
  const startPageY = event.pageY
  // 创建临时拖拽元素
  const dragElement = document.createElement('img')
  dragElement.src = item.image || ''
  dragElement.style.position = 'absolute'
  dragElement.style.pointerEvents = 'none'
  dragElement.style.width = '50px'
  dragElement.style.height = '50px'

  document.body.style.cursor = 'all-scroll'
  document.body.appendChild(dragElement)

  const handleMoveElement = (e: { clientX: any; clientY: any }) => {
    const left = e.clientX
    const top = e.clientY
    dragElement.style.left = `${left}px`
    dragElement.style.top = `${top}px`
  }

  const handleMoveUpElement = (e: { pageX: any; pageY: any }) => {
    const endPageX = e.pageX
    const endPageY = e.pageY
    const minSize = 30

    const defaultSize = 200
    const minX = Math.min(endPageX, startPageX)
    const minY = Math.min(endPageY, startPageY * 3)
    const maxX = Math.max(endPageX, startPageX)
    const maxY = Math.max(endPageY, startPageY * 3)
    const offsetX = maxX - minX >= minSize ? maxX - minX : defaultSize
    const offsetY = maxY - minY >= minSize ? maxY - minY : defaultSize

    const start = [minX, minY] as [number, number]
    const end = [minX + offsetX, minY + offsetY] as [number, number]
    const result = formatCreateSelection({ start, end })
    if (!result) return
    const { left, top } = result
    item.add!(left, top)
    document.removeEventListener('mousemove', handleMoveElement)
    document.removeEventListener('mouseup', handleMoveUpElement)
    document.body.removeChild(dragElement)
    document.body.style.cursor = 'default'
  }

  document.addEventListener('mousemove', handleMoveElement)
  document.addEventListener('mouseup', handleMoveUpElement)
}
</script>

<style lang="scss" scoped>
.layout-pool {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 20px;

  .default-layout {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 6px 12px;
    padding-bottom: 20px;
  }

  .full-layout {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    gap: 6px 12px;
    padding-bottom: 20px;
    font-weight: bold;

    .flex-container {
      height: 100px;
    }

    .right-container {
      padding: 0 8px;
    }

    .right-bottom-element {
      justify-content: center;
      flex: 3;
      align-items: flex-start;
      line-height: 5;
    }
  }

  .flex-container {
    display: flex;
    margin-top: 12px;
    height: 50px;
    background-color: #fafbfc;
    box-shadow: 3px 3px 8px 0px rgba(0, 0, 0, 0.4);
    overflow: hidden;
  }

  .left-element {
    flex: 1;
    // background-color: #f0f0f0;
    padding: 10px;
  }

  .right-container {
    flex: 3;
    display: flex;
    flex-direction: column;
    text-align: right;
    padding-right: 8px;
    font-size: 10px;
    line-height: 25px;
  }

  .right-top-element,
  .right-bottom-element {
    line-height: 1;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    text-align: left;
    // background-color: #d0d0d0;
  }

  .footer {
    flex: 1;
    width: 100%;
    display: flex;
    justify-content: center;
    gap: 24px;
  }

  img {
    width: 30px;
    height: 30px;
  }
}
</style>
